import {
	login,
	logout,
	getInfo
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'

import {
	listSchool,
} from "@/api/bbs_school/school";
import {
		getAllSchools,
	} from "@/api/bbs_user/bbs_user";
import schoolInfoList from '../../utils/schoolInfo.js'

const user = {
	state: {
		token: getToken(),
		name: '',
		avatar: '',
		roles: [],
		permissions: [],
		currentSchool: {},
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, name) => {
			state.name = name
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
		},
		SET_currentSchool: (state, currentSchool) => {
			state.currentSchool = currentSchool
		}
	},

	actions: {
		// 登录
		Login({
			commit
		}, userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid
			return new Promise((resolve, reject) => {
				login(username, password, code, uuid).then(res => {
					setToken(res.token)
					commit('SET_TOKEN', res.token)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const user = res.user
					const avatar = (user.avatar == "" || user.avatar == null) ? require(
							"@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user
						.avatar;
					if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
						commit('SET_ROLES', res.roles)
						commit('SET_PERMISSIONS', res.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_NAME', user.userName)
					commit('SET_AVATAR', avatar)
					//获取学校列表和学校基础信息
					// console.log("本地学校信息",schoolInfoList.schoolInfoList)
					let schoolListParams = {
						pageNum: 1,
						pageSize: 100,
					}
					// listSchool(schoolListParams).then(response => {
					getAllSchools().then(response => {
						console.log("获取学校列表", response)
						let schoolList = response.data
						//标志管理员是否找到了自己管理的学校
						let findSchool = 0;
						let schoolInfo = {}
						for (var m = 0; m < res.roles.length; m++) {
							// console.log('哈哈哈',res.roles[m])
							//超级管理员
							if (res.roles[m] == 'admin') {
								//学校列表的第一个学校信息
								for (var n = 0; n < schoolInfoList.schoolInfoList.length; n++) {
									// console.log('哈哈哈',n,schoolInfoList.schoolInfoList[n].schoolid,schoolList[0].schoolid)
									if (schoolInfoList.schoolInfoList[n].schoolid ==schoolList[0].schoolid) {
										schoolInfo = schoolInfoList.schoolInfoList[n]
										findSchool=1
										break
									}
								}
								//全局学校信息
								commit('SET_currentSchool', schoolInfo)
								break
							}
						}
						// //全局学校信息
						// commit('SET_currentSchool', schoolInfo)
						//获取各学校basic配置项
						for (var i = 0; i < schoolList.length; i++) {
							let schoolName = schoolList[i].schoolname
							
							//获取基础配置并写入本地文件中
							let tempInfoObject = {
								name: null,
								value: null,
								schoolid: null,
								adminUserId: null, //暂时不会使用
								templateId: null,
								APPID: null,
								//cloudAppId作用为访问云数据库
								cloudAppId: null,
								envId: null,
								personInChargeWX:null,
							}
							//赋值
							tempInfoObject.name = schoolName;
							tempInfoObject.value = schoolList[i].schoolid * 1;
							tempInfoObject.schoolid = schoolList[i].schoolid *1;
							
							//在本地学校信息中新增
							schoolInfoList.schoolInfoList.push(tempInfoObject)
							// let schoolInfo = {}
							for (var m = 0; m < res.roles.length; m++) {
								// console.log('哈哈哈',res.roles[m])
								//超级管理员
								if (res.roles[m] == 'admin') {
									//学校列表的第一个学校信息
									for (var n = 0; n < schoolInfoList.schoolInfoList.length; n++) {
										// console.log('哈哈哈',n,schoolInfoList.schoolInfoList[n].schoolid,schoolList[0].schoolid)
										if (schoolInfoList.schoolInfoList[n].schoolid ==schoolList[0].schoolid) {
											schoolInfo = schoolInfoList.schoolInfoList[n]
											break
										}
									}
									findSchool=1
									//全局学校信息
									commit('SET_currentSchool', schoolInfo)
									break
								}
							}
							// //全局学校信息
							// commit('SET_currentSchool', schoolInfo)
							//将当前管理员的学校信息配置给他
							if (findSchool == 0) {
								for (var i = 0; i < res.roles.length; i++) {
									// console.log("判断管理员身份",res.roles[i],basicConfig.schoolId)
									// if (res.roles[i].includes(basicConfig.schoolId)) {
									// 	console.log("这是", schoolName,"的管理员")
									// 	commit('SET_currentSchool',tempInfoObject)
									// 	findSchool = 1
									// 	break
									// }
									if (res.roles[i].length > 6) {
									    // 如果长度大于6，则从第6位开始分割字符串
									    // return this.originalString.substring(0, 6);
										// console.log("判断管理员身份",res.roles[i],res.roles[i].substring(0, 5),res.roles[i].substring(5))
										if (res.roles[i].substring(0, 5)=='xygly' && res.roles[i].substring(5)==basicConfig.schoolId ) {
											commit('SET_currentSchool',tempInfoObject)
											console.log("这是", schoolName,"的管理员",)
											findSchool = 1
											break
										}
									} else {
									    // 如果长度不大于6，则返回原始字符串
									    // return this.originalString;
									}
								}
							}
						} //获取学校配置项并写入本地文件结束

						

					});
					//获取学校信息结束
					
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					removeToken()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 前端 登出
		FedLogOut({
			commit
		}) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '')
				removeToken()
				resolve()
			})
		}
	}
}

export default user
